<template>
    <div class = 'predict-wrapper jimu-map-panel jimu-show' v-show = "isShow"> 
		<div class = "panel-close" @click = "close">
			<i class="iconfont icon-close"></i>
		</div>
		<div class="list-container">
			<count-up v-for="index in indexList" :key = "index.key"
				:titleName="index.name"
				:countNum="valObj[index.key]"
			></count-up>
			<div class="count-title">商圈范围内人口分布</div>
			<div class="chart-container" ref="chartNode"></div>
		</div>
    </div>
</template>

<script>
import BaseWidget from '@/jimu/BaseWidget.js'
import CountUp from './components/CountUp'
import {retail as retailAPI, data as dataAPI} from '@/api'
const echarts = require('echarts/lib/echarts');
require('echarts/lib/chart/pie')
require('echarts/lib/component/tooltip')
require('echarts/lib/component/legend')
export default {
	name: 'PredictWidget',
	mixins:[ BaseWidget ],
	data(){
		return {
			valObj:{
				ttl_sales: 0,
			} ,
			disabled:false,
			popNode: null,
			test: 2,
			chart: null,
			chartOption: {
				color:["#009ff8","#ffca00"],
				tooltip: {
					trigger: 'item',
					formatter: "{a} <br/>{b}: {c} ({d}%)"
				},
				legend: {
					top: 'bottom',
					data:['工作人口','居住人口']
				},
				series: [
					{
						name:'人口分布',
						type:'pie',
						label: {
							show: false
						},
						data:[
							{value:0, name:'工作人口'},
							{value:0, name:'居住人口'}
						]
					}
				]
			}
		}
	},
	created() {
		this.subscribe()
		this.initValObj()
		this.limitDistrict()
	},

	computed:{
		indexList () {
			return this.config.indexList
		},
		map: function(){
			return this.shareState.map
		}
	},
	mounted() {
		this.bindMapClickEvent()
		this.initChart()
		this.popNode = this.createPopPanelNode()
		this.map._container.style.cursor='crosshair'
	},

	destroyed(){
		this.map.unbind('click', this.mapClick);
        this.map.unbind('mousemove', this.mouseMoveHandle)
        this.map.unbind('mouseleave', this.mouseLeaveHandle)
        if(this.pointLayer){
            this.pointLayer.clear()
            this.pointLayer.remove()
		}
		if(this.limitLayer){
            this.limitLayer.clear()
            this.limitLayer.remove()
		}
		if(this.taLayer){
            this.taLayer.clear()
            this.taLayer.remove()
        }
		if(this.hubLayer){
            this.hubLayer.clear()
            this.hubLayer.remove()
        }
        this.map._container.style.cursor='default'
        this.map._container.removeChild(this.popNode)
		this.popNode = null
		this.bus.$emit(this.event.CLOSE_WIDGET, 'predict-legend')
	},

	components:{
		'count-up': CountUp
	},

	methods:{
		subscribe: function() {
			this.bus.$on("toggle-layer", (key) => {
				if(!this[key+'Layer']) return
				if(this[key+'Layer'].isVisible()){
					this[key+'Layer'].hide()
				}else{
					this[key+'Layer'].show()
				}
			})
		},

		initValObj: function() {
			this.indexList.forEach(index => {
				this.valObj[index.key] = 0
			})
		},

		initChart: function() {
			this.chart = echarts.init(this.$refs.chartNode)
			this.chart.setOption(this.chartOption)
		},

		setRandomVal: function() {
			this.indexList.forEach(index => {
				this.$set(this.valObj, index.key, parseInt(Math.random()*10000))
			})
		},

		bindMapClickEvent: function(){
            this.map.bind('click', this.mapClick)
            this.map.bind('mousemove', this.mouseMoveHandle)
            this.map.bind('mouseleave', this.mouseLeaveHandle)
		},
		createPopPanelNode: function(){
            let elNode = document.createElement("div")
            elNode.innerHTML = "点击进行销售额预测"
            elNode.style.position = "absolute"
            elNode.style.display = "none"
            elNode.style.padding = "5px 8px"
            elNode.style.fontSize = "10px"
            elNode.style.backgroundColor = "rgba(67, 81, 93, 0.7)"
            elNode.style.color = "#fff"
            elNode.style.border = "2px solid #4087f7"
            elNode.style.borderRadius = "4px"
            this.map._container.appendChild(elNode)
            return elNode
		},
		mapClick(event){
            if (this.disabled) {
                return
            }
            this.location = [event.mapX, event.mapY]
			this.addCenterPoint()
			this.startPredict(this.location)
            
        },
		mouseMoveHandle: function(e){
            this.popNode.style.display = "block"
            let top,left
            if(e.screenX + this.popNode.offsetWidth < (this.map._container.clientWidth-5)){
                left = e.screenX + 5
            }else{
                left = e.screenX - this.popNode.offsetWidth - 5
            }
            if(e.screenY + this.popNode.offsetHeight < (this.map._container.clientHeight-5)){
                top = e.screenY + 5
            }else{
                top = e.screenY - this.popNode.offsetHeight - 5
            }

            this.popNode.style.left =left + "px"
            this.popNode.style.top = top + "px"
        },

        mouseLeaveHandle: function(){
            this.popNode.style.display = "none"
		},
		
		addCenterPoint: function(){
			if(!this.pointLayer){
				this.pointLayer = (new G.Layer.Graphic()).addTo(this.map);
			}
            this.pointLayer.clear()
            let point = new G.Graphic.Point(this.location, null, this.config.pointConfig)
            point.addTo(this.pointLayer)
		},
		startPredict: function(location) {
			let lngLat = G.Proj.WebMercator.unproject(location[0],location[1])
			this.disabled = true
			this.bus.$emit("showLoading", true)
			let params = {
				x: lngLat[0],
				y: lngLat[1]
			}
			retailAPI.predict(params).then((res)=>{
				this.bus.$emit("showLoading", false)
				this.disabled = false
				let data = res.data.data
				this.valObj['ttl_sales'] = data.sales.pre_fc_mall + data.sales.pre_fc_sr + data.sales.pre_mds
				this.valObj['traffic100'] = data.population.traffic100
				this.valObj['mpp_ta'] = data.population.mpp_ta
				let chartData = [
					{
						value: data.population.work_ta, 
						name:'工作人口'
					},
					{
						value: data.population.home_ta, 
						name:'居住人口'
					}
				]
				this.chartOption.series[0].data = chartData
				this.chart.setOption(this.chartOption)
				this.drawTaHub(data.geoms)
				this.bus.$emit(this.event.OPEN_WIDGET, 'predict-legend')
			}).catch((error)=>{
				console.log(error)
				this.bus.$emit("showLoading", false)
				this.disabled = false
			})
		},

		limitDistrict: function(){
			if(!this.limitLayer){
                this.limitLayer = (new G.Layer.Graphic()).addTo(this.map)
            }
			dataAPI.query('b4c1fb501d5811e9a554ff52123ae837',{}).then((res)=>{
				if(res.data.code !== 0) return
				let features = res.data.data.features
				features.forEach((feature) => {
					let g = new G.Graphic.MultiPolygon(feature.geom, feature.attrs, this.config.polygonStyle)
					g.addTo(this.limitLayer)
				})
				this.limitExtent = this.limitLayer.calcDataExtent()
				this.map.zoomExtent(this.limitExtent)
			})
		},

		drawTaHub: function(geoms) {
			if(!this.map) return
			if(!this.hubLayer){
				this.hubLayer = (new G.Layer.Graphic()).addTo(this.map);
				this.hubLayer.bringDown(1)
			}
			if(!this.taLayer){
				this.taLayer = (new G.Layer.Graphic()).addTo(this.map);
				this.taLayer.bringDown(1)
			}
			if(!this.taLayer.isVisible()){
				this.taLayer.show()
			}
			if(!this.hubLayer.isVisible()){
				this.hubLayer.show()
			}
			this.taLayer.clear()
			this.hubLayer.clear()
			let taGraphic =  new G.Graphic.Polygon([geoms.ta], '', this.config.taStyle)
			let hubGraphic =  new G.Graphic.Polygon([geoms.hub], '', this.config.hubStyle)
			hubGraphic.addTo(this.hubLayer)
			taGraphic.addTo(this.taLayer)
			this.map.zoomExtent(this.hubLayer.calcDataExtent())
		}
	}
	
}
</script>

<style lang="scss">
.predict-wrapper{
	padding:15px 15px 10px 15px;
	width:230px;
	z-index: 999;
	position: absolute;
	right:10px;
	top:10px;
	
	.panel-close{
		height:20px;
		width:20px;
		text-align: center;
		line-height: 20px;
		position: absolute;
		right:10px;
		top:10px;
		cursor: pointer;
	}
	.count-title{
        font-weight: 700;
        border-left: 4px #1e9cf3 solid;
        padding-left: 5px;
    }
	.chart-container{
		height: 225px;
	}
}
</style>